package com.zjsy.controller;

import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.pdfbox.multipdf.Splitter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.util.GraphicsRenderingHints;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import com.zjsy.page.PageBean;
import com.zjsy.po.Magazine;
import com.zjsy.po.MagazineNewList;
import com.zjsy.po.MagazineNews;
import com.zjsy.po.MainNews;
import com.zjsy.po.MainNewsList;
import com.zjsy.po.MainNewsModule;
import com.zjsy.po.Message;
import com.zjsy.po.WeChatNewsList;
import com.zjsy.service.MagazineService;
import com.zjsy.service.MainNewsService;

@Controller
public class MagazineController {

    private static final Logger log = LoggerFactory.getLogger(MagazineController.class);
    @Autowired
    private MagazineService magazineServicel;

    //获取当前页的页码
    private int getPc(HttpServletRequest req) {
        int pc = 1;
        String param = req.getParameter("pc");
        if (param != null && !param.trim().isEmpty()) {
            try {
                pc = Integer.parseInt(param);
            } catch (RuntimeException e) {

            }
        }
        return pc;
    }

    //截取url，页面中的分页导航中要使用它作为超链接的目标
    private String getUrl(HttpServletRequest req) {
        String url = req.getRequestURL() + "?" + req.getQueryString();
        //如果url中存在pc参数
        int index = url.lastIndexOf("&pc=");
        //这步的意思是把如果url中存在pc参数的话，就把pc这个参数去掉，因为上面getPc已经获取pc这个变量值
        if (index != -1) {
            url = url.substring(0, index);
        }
        return url;
    }


    @RequestMapping("/magazine-edit")
    public String magazineEdit(HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("id");
        Magazine magazine = magazineServicel.findMagazineById(id);
        req.setAttribute("Magazine", magazine);
        return "magazine-edit";
    }

    @RequestMapping("/magazinenew-edit")
    public String magazinenewEdit(HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("id");
        MagazineNews magazinenews = magazineServicel.findMagazineNewsById(id);
        req.setAttribute("Magazinenews", magazinenews);
        return "magazineNews-edit";
    }


    @RequestMapping("/deleteMagazine")
    @ResponseBody
    public Message deleteMagazine(HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("id");
        magazineServicel.deleteMagazineById(id);
        return new Message("删除成功");
    }

    @RequestMapping("/deleteMagazineNews")
    @ResponseBody
    public Message deleteMagazineNews(HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("id");
        magazineServicel.deleteMagazineNewsById(id);
        return new Message("删除成功");
    }


    @RequestMapping("updataMagazine")
    @ResponseBody
    public Message updataMagazine(HttpServletRequest req, HttpServletResponse resp, @RequestBody Magazine magazine) {
        magazineServicel.updateMagezine(magazine);
        return new Message("更新成功");
    }

    @RequestMapping("updataMagazineNews")
    @ResponseBody
    public Message updataMagazineNews(HttpServletRequest req, HttpServletResponse resp, @RequestBody MagazineNews magazinenews) {
        magazineServicel.updateMagazineNews(magazinenews);
        return new Message("更新成功");
    }


    @RequestMapping("/magazine-list")
    public String magazineList(HttpServletRequest req, HttpServletResponse resp) {
        int pc = getPc(req);
        String url = getUrl(req);
        PageBean<Magazine> List = magazineServicel.findMagazineByPage(pc);
        List.setUrl(url);
        req.setAttribute("List", List);
        return "magazine-list";
    }

    @RequestMapping("/magazine-add")
    public String magazineAdd() {
        return "magazine-add";
    }

    @RequestMapping(value = "/uppdf", method = {RequestMethod.POST})
    @ResponseBody
    public Object headImg(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {

        Map<String, Object> map2 = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        //保存上传
        try {
            if (file != null) {
                //原pdf文件存储
                String originalName = file.getOriginalFilename();
                System.out.println(originalName);
                String filepath = "C:\\Users\\Messi\\IdeaProjects\\zjsy\\pdf\\" + originalName;
                System.out.println(filepath);
                filepath = filepath.replace("\\", "/");
                File files = new File(filepath);
                if (!files.getParentFile().exists()) {
                    files.getParentFile().mkdirs();
                }
                file.transferTo(files);

                ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
                executor.setCorePoolSize(5); // 核心线程数
                executor.setMaxPoolSize(10); // 最大线程数
                executor.setQueueCapacity(25); // 线程队列容量
                executor.setThreadNamePrefix("AsyncThread-"); // 线程名称前缀
                executor.initialize();
                executor.execute(()->{
                    //发起请求
                    RestTemplate restTemplate = new RestTemplate();
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
                    MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
                    body.add("file", new FileSystemResource(files));
                    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
                    ResponseEntity<String> response1 = restTemplate.exchange(
                            "http://localhost:8085/user/upload", HttpMethod.POST, requestEntity, String.class);
                    System.out.println(response1.getStatusCode());
                });
                System.out.println("======================完成============================");
                map.put("code", 0);
                map.put("msg", "");
                map.put("data", map2);
                map2.put("pdfurl", "/pdf/" + originalName.substring(0,originalName.indexOf(".")));
            }
        } catch (Exception e) {
            log.debug(e.getMessage());
        }

        return map;
    }


    @RequestMapping("/addMagazine")
    @ResponseBody
    public Message addMagazine(HttpServletRequest req, HttpServletResponse resp, @RequestBody Magazine magazine) {

        magazineServicel.addMagazine(magazine);


        return new Message("添加杂志成功");
    }


    @RequestMapping("/addMagazineNews")
    @ResponseBody
    public Message addMagazineNews(HttpServletRequest req, HttpServletResponse resp, @RequestBody MagazineNews magazinenews) {


        magazineServicel.addMagazineNews(magazinenews);


        return new Message("添加杂志成功");
    }


    @RequestMapping("/magazinenew-list")
    public String weChatlList(HttpServletRequest req, HttpServletResponse resp) {

        int pc = getPc(req);
        String url = getUrl(req);
        PageBean<MagazineNewList> List = magazineServicel.findMagazineNewByPage(pc);
        List.setUrl(url);
        req.setAttribute("List", List);
        return "magazinenew-list";
    }


    @RequestMapping("/magazineNews-add")
    public String MagazineNewsAdd(HttpServletRequest req, HttpServletResponse resp) {

        return "magazineNews-add";
    }

    public void convertPdfToPng(MultipartFile file, String outputPath) throws IOException {
        // 创建输出目录
        File outputDir = new File(outputPath);
        if (!outputDir.exists()) {
            if (!outputDir.mkdirs()) {
                throw new IOException("无法创建输出目录: " + outputPath);
            }
        }

        // 生成临时文件
        File tempFile = File.createTempFile("temp", ".pdf");
        file.transferTo(tempFile);

        try (PDDocument document = PDDocument.load(tempFile)) {
            Splitter splitter = new Splitter();
            List<PDDocument> pages = splitter.split(document);
            int pageIndex = 1;
            for (PDDocument page : pages) {
                PDFRenderer renderer = new PDFRenderer(page);
                BufferedImage image = renderer.renderImageWithDPI(0, 300, ImageType.RGB);
                // 写入图像文件
                File outputImage = new File(outputPath, "page" + pageIndex + ".png");
                System.out.println("page" + pageIndex + ".png");
                ImageIO.write(image, "png", outputImage);
                pageIndex++;
                page.close();
                image.flush();
            }
        } catch (Exception e){
            log.debug(e.getMessage());
        } finally{
            // 删除临时文件
            if (!tempFile.delete()) {
                System.err.println("临时文件删除失败: " + tempFile.getAbsolutePath());
            }
        }
    }


}
